package project1.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.util.*;

public class FileUpLoadUtils {
    public static Map<String,Object> parseRequesment(HttpServletRequest request){
    //看看请求是否有entype属性
    //request.setCharacterEnconding("utf-8");
        boolean multipartContent = ServletFileUpload.isMultipartContent(request);
        if (!multipartContent){
            return null;
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置缓存地址，比如上传的文件非常大，缓存下来再慢慢处理
        ServletContext servletContext = request.getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);
        ServletFileUpload upload = new ServletFileUpload(factory);
        //如果上传的文件中有中文乱码，解决方案
        upload.setHeaderEncoding("utf-8");
        //bytes
        //upload.setFileSizeMax(1024);
        //Parse the request
        Map<String,Object> params = new HashMap<String, Object>();
        try {
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()){
                //每个item就是对每个input的封装
                FileItem item = iterator.next();
                if (item.isFormField()){
                    //看一下是否普通的form表单数据
                    processFormField(item,params);
                }else{
                    //上传的文件
                    processUploadFile(item,params,request);
                }
            }
            //JDBC
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        return params;
    }

    /**
     *对文件名称进行散列hashcode int尽可能的分散的很开
     *对这个int取16进制形式8位，upload 1 4 a 5 9 8 5 f --file 16^8 100万个文件
     * @param item
     * @param map
     * @param request
     */
    private static void processUploadFile(FileItem item, Map<String, Object> map, HttpServletRequest request) {
    //散列 分散开 hashcode
        String upload_prefix = "upload";
        String fieldName = item.getFieldName();
        String fileName = item.getName();
        fileName = UUID.randomUUID().toString() + "-" + fileName;
        int hashCode = fileName.hashCode();
        //hash值得16进制表现形式
        String hexString =Integer.toHexString(hashCode);
        char[] charArray = hexString.toCharArray();
        for (char c : charArray){
            upload_prefix = upload_prefix + "/" + c;
        }
        String contentType = item.getContentType();
        boolean isInMemory = item.isInMemory();
        long sizeInBytes = item.getSize();
        System.out.println(fieldName + "," + fileName + "," + contentType + "," + isInMemory + "," +sizeInBytes);
        //将文件保存在upload目录下
        String relativePath = upload_prefix + "/" + fileName;
        String realPath = request.getServletContext().getRealPath(relativePath);
        File file = new File(realPath);
        if (!file.getParentFile().exists()){
         file.getParentFile().mkdirs();
        }
        try {
            item.write(file);
            map.put(fieldName,relativePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *处理常规form表单数据得逻辑
     * @param item
     * @param params
     */
    private static void processFormField(FileItem item, Map<String, Object> map) {
        String name = item.getFieldName();
        String value = null;
        try {
            value = item.getString("utf-8");
            map.put(name,value);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(name + "=" + value);
    }

}
